/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.io.comm;

/**
 * Class to calculate and store information returned by a Pasv ftp command.
 * 
 */
class PasvInfo {
	/**
	 * After instantiation this field contains the ip address to connect to.
	 */
	String ip;
	/**
	 * After instantiation this field contains the port to connect to.
	 */
	int port;

	/**
	 * Create an instance of PasvInfo. After successful instantiation the fields
	 * port and ip can be read. If the dataLink string is badly formatted, an
	 * FtpProtocolException is thrown.
	 * 
	 * @param dataLink
	 *            The part of the response string after PASV which between the
	 *            brackets.
	 */
	PasvInfo(String dataLink) throws FTPException {
		StringBuffer sb = new StringBuffer();
		int pass = 0;
		int i = 0;
		char current;
		// IP cím
		while (pass < 4 && i < dataLink.length()) {
			current = dataLink.charAt(i);
			if (current != ',') {
				sb.append(current);
			} else {
				if (pass < 3) {
					sb.append('.');
				}
				pass++;
			}
			i++;
		}
		// Has everything went fine?
		if (i >= dataLink.length()) {
			throw new FTPException("FTPException: Received badly formatted answer to PASV command");
		}
		this.ip = sb.toString();
		pass = 0;
		int port1 = 0;
		int port2 = 0;
		while (pass < 2 && i < dataLink.length()) {
			current = dataLink.charAt(i);
			if (current != ',') {
				if (pass == 0) {
					port1 = port1 * 10 + (current - 48);
				} else {
					port2 = port2 * 10 + (current - 48);
				}
			} else {
				pass++;
			}
			i++;
		}
		if (pass != 1) {
			throw new FTPException("FTPException: Received badly formatted answer to PASV command");
		}
		port = port1 * 256 + port2;
	}
}
